import passport from '@/api/modules/passport'
import feedback from '@/utils/feedback'
import router from '@/router'
import { useAuthStore } from '@/stores/modules/auth'
import { useMenuStore } from '@/stores/modules/menu'

export function useLogin() {
    const isLogin = ref(false)
    const authStore = useAuthStore()
    const menuStore = useMenuStore()

    /**
     * 登录获取TOKEN
     */
    async function getToken(data: any) {
        isLogin.value = true
        const user = await passport.getToken.post(data, { await: 1 })
        if (!user) {
            isLogin.value = false
            return false
        }
        authStore.token = user.adminToken
        authStore.userInfo = user.adminInfo

        return true
    }

    /**
     * 登录获取菜单
     */
    async function getSystemMenu() {
        try {
            const result = await passport.getSystemMenu.get({}, { await: 1 })
            if (!result) {
                throw new Error('登录获取菜单失败')
            }

            if (result.menu.length == 0) {
                throw new Error('当前用户无任何菜单权限，请联系系统管理员')
            }

            menuStore.menu = result.menu
            menuStore.permissions = result.permissions
            menuStore.dashboardGrid = result.dashboardGrid

            menuStore.isRoutesLoaded = false

            await router.replace({ path: '/' })
            feedback.success('登录成功')
        } catch (error: any) {
            feedback.error(error.message || '登录失败，请重试')
            return false
        } finally {
            isLogin.value = false
        }
    }

    return {
        isLogin,
        getToken,
        getSystemMenu
    }
}
